/* TaskManager.java
 *
 * Project/Product: GW
 *
 * Modify Information:
 * =============================================================================
 *   Author	Date       Description
 *   ----------	---------- ---------------------------------------------------
 *   Administrator	2008-5-29	First release
 *
 * Licensed Materials - Property of APEP
 * =============================================================================
 *    (C) COPYRIGHT Shanghai Auto Mart E-Procurement Co., Ltd. 2007 - 2008
 *    All Rights Reserved.
 *
 *    This software is the confidential and proprietary information of
 *    Shanghai Auto Mart E-Procurement Co., Ltd. ("Confidential Information").
 *    You shall not disclose such Confidential Information and shall use it only
 *    in accordance with the terms of the license agreement you entered into 
 *    with Shanghai Auto Mart E-Procurement Co., Ltd.
 *
 * Noties:
 * =============================================================================
 * 
 */

package system.servlet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import system.base.StorageMonthOutTask;
import system.schedule.CategoryClearTask;


public class TaskManager implements ServletContextListener {

    /** 每天的毫秒数  */
    public static final long PERIOD_DAY = 86400;
    
    public static final long USEING = 1728000000;
    
    public static final long PERIOD_ONE_DAY = 86400000;

    /** 一周内的毫秒数 */
    public static final long PERIOD_WEEK = PERIOD_DAY * 7;

    /** 无延迟 */
    public static final long NO_DELAY = 0;

    /** 定时器 */
    private Timer timer;
    
    /** 定时器 */
    private Timer categoryClearTimer;

    /** 在Web应用启动时初始化任务  */
    public void contextInitialized(ServletContextEvent event) {
        //定义定时器
        timer = new Timer(true);
        //
        timer.schedule(new StorageMonthOutTask(), 60000, USEING);
        
        
        final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd '21:35:00'");
    
        try {
			Date startTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
			if(System.currentTimeMillis()>startTime.getTime())
				startTime=new Date(startTime.getTime()+PERIOD_ONE_DAY);
			categoryClearTimer=new Timer(true);
			categoryClearTimer.scheduleAtFixedRate(new CategoryClearTask(), startTime, PERIOD_ONE_DAY);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    }

    /**
     * 在Web应用结束时停止任务
     */
    public void contextDestroyed(ServletContextEvent event) {
        timer.cancel(); // 定时器销毁
        categoryClearTimer.cancel();
    }
}
